<template>
	<el-button :disabled="isDisabled">
		{{ buttonText }}
	</el-button>
</template>

<script lang="ts" setup>
// 延时按钮, 倒计时按钮, 倒计时3秒后才可以点击
import { ref, computed, onBeforeUnmount, onMounted } from 'vue';

defineOptions({
	name: 'MkButtonDelay'
})


const isDisabled = ref(true);
let countdown = 3; // 倒计时时长，单位为秒
let doCount = true;

let timer = setInterval(() => {
	if (doCount) {
		countdown -= 1;
		if (countdown <= 0) {
			doCount = false;//停止倒计时
			isDisabled.value = false;//按钮可用
		}
	}
}, 1000);

const buttonText = computed(() => {
	return isDisabled.value ? ` ${countdown} ` : '确 定';
});

// 启动倒计时
const startCountdown = () => {
	countdown = 3; //重置倒计时
	doCount = true;//开始倒计时
	isDisabled.value = true;//按钮不可用
};

onMounted(() => {
	startCountdown();
});

// 组件销毁前清除计时器，防止内存泄漏
onBeforeUnmount(() => {
	if (timer) {
		clearInterval(timer);
	}
});

defineExpose({
	startCountdown
})
</script>